<template>
    <div class="product-add" v-loading="loading">
        <!--form表单-->
        <div class="common-form">添加会员券包</div>
        <el-form size="small" ref="form" :rules="rules" :model="form" label-width="200px">
            <el-form-item label="会员券包标题" prop="title">
                <el-input v-model="form.title" :disabled="disabled" />
            </el-form-item>
            <el-form-item label="会员券包价格" prop="price">
                <el-input-number :min="0" v-model="form.price" :disabled="disabled" />
            </el-form-item>
            <el-form-item label="用户可购买次数" prop="maxBuyCount">
                <el-input-number :min="0" v-model="form.maxBuyCount" :disabled="disabled" />
            </el-form-item>
            <el-form-item label="券包等级" prop="gradeId">
                <el-select v-model="form.gradeId" :disabled="disabled">
                    <el-option v-for="item in leves" :label="item.name" :value="item.gradeId" :key="item.gradeId">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="赠送余额" prop="giveBalance">
                <el-input-number :min="0" v-model="form.giveBalance" :disabled="disabled" />
            </el-form-item>
            <el-form-item label="排序" prop="sort">
                <el-input-number :min="0" v-model="form.sort" :disabled="disabled" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-switch v-model="form.status" :disabled="disabled" active-text="有效" inactive-text="无效"
                    :active-value="1" :inactive-value="0" />
            </el-form-item>
            <el-form-item label="选择抵扣券" prop="gridData">
                <el-button @click="handlerSelect" style="margin: 10px;" v-if="!disabled">选择</el-button>
                <!-- 明细数据 -->
                <el-table :data="gridData" ref="tableRef" border stripe>
                    <el-table-column type="selection" />
                    <el-table-column property="name" label="优惠券名称" />
                    <el-table-column property="couponTypeText" label="优惠券类型" />
                    <el-table-column property="color" label="优惠券颜色">
                        <template #default="scope">
                            <el-tag>{{ colorDic[scope.row.color] }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column property="reducePrice" label="减免金额" />
                    <el-table-column property="minPrice" label="最低消费金额" width="160" />
                    <el-table-column property="discount" label="折扣率%" />
                    <el-table-column property="bigPrice" label="最多优惠多少元" width="160" />
                    <el-table-column property="cancelType" label="核销券类型">
                        <template #default="scope">
                            <el-tag v-if="scope.row.cancelType !== null && scope.row.couponType === 30">
                                {{ hxOptions[scope.row.cancelType] }}</el-tag>
                            <div v-else></div>
                        </template>

                    </el-table-column>
                    <el-table-column property="isCanShare" label="是否可分享">
                        <template #default="scope">
                            <el-tag>{{ scope.row.isCanShare === 0 ? '不可分享' : '可分享' }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column property="superimpose" label="可叠加">
                        <template #default="scope">
                            <el-tag>{{ scope.row.isCanShare === 0 ? '不可叠加' : '可叠加' }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column property="expireDay" label="有效天数" />
                    <el-table-column property="totalNum" label="发放总量" />
                    <el-table-column property="num" label="数量" width="150">
                        <template #default="scope">
                            <el-input-number v-model="scope.row.num" :disabled="disabled" :min="0"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column property="control" label="操作" v-if="!disabled">
                        <template #default="scope">
                            <el-button size="small" type="danger" @click="handlerRemove(scope.$index)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <div class="common-button-wrapper">
                <el-button size="small" type="info" @click="cancelFunc">取消</el-button>
                <el-button size="small" type="primary" @click="onSubmit" v-if="!disabled">提交</el-button>
            </div>
        </el-form>
        <couponSelect :show="show" @onCancle="onSelectCancle" @onSave="onSelectSave"></couponSelect>
    </div>
</template>
<script>
import couponSelect from './couponSelect.vue';
import PackageApi from '@/api/package'
import { ElMessage } from 'element-plus'
export default {
    components: {
        couponSelect
    },
    props: {
        editId: {
            type: String,
            default: ''
        },
        disabled: {
            type: Boolean,
            default: false
        }
    },
    watch: {
        editId: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.getDetail(val)
                }
            }
        }
    },
    data() {
        return {
            /*切换菜单*/
            // activeIndex: '1',
            /*form表单数据*/
            hxOptions: {
                0: '肥料券',
                1: '参观券',
                2: '指导券'
            },
            form: {
                id: '',
                title: '',
                maxBuyCount: 0,
                price: 0,
                gradeId: '',
                giveBalance: 0,
                sort: 1,
                status: 1,
                gridData: []
            },
            rules: {
                title: [
                    { required: true, message: '请输入券包标题', trigger: 'blur' },
                ],
                price: [
                    { required: true, message: '请输入券包价格', trigger: 'blur' },
                ],
                maxBuyCount: [
                    { required: true, message: '请输入最大购买数量', trigger: 'blur' },
                ],
                gradeId: [
                    { required: true, message: '请选择会员等级', trigger: 'blur' },
                ]
            },
            colorDic: {
                10: '蓝色',
                20: '红色',
                30: '紫色',
                40: '黄色'
            },
            show: false,
            manJianData: [],
            columnsData: [],
            gridData: [],
            leves: [],
            couponData: [],
            loading: false
        };
    },
    created() {
        this.loadLevels()
    },

    methods: {
        loadLevels() {
            const $this = this
            PackageApi.getAllGrade()
                .then(result => {
                    const { code, data } = result
                    if (code === 1) {
                        $this.leves = data
                    }
                })
        },
        cancelFunc() {
            this.$router.back()
        },
        getDetail(id) {
            const $this = this
            $this.loading = true
            PackageApi.getCouponPackDetail(id)
                .then(result => {
                    $this.loading = false
                    const { code, data } = result
                    if (code === 1) {
                        $this.form = data
                        $this.gridData = data.couponPackageVos ?? []
                    }
                })
        },
        handlerSelect() {
            this.show = true
        },
        onSelectCancle() {
            this.show = false
        },
        onSelectSave(data) {
            this.show = false
            const $this = this
            const defaultData = $this.gridData
            if (data) {
                const { rows } = data
                const arry = defaultData
                if (rows) {
                    rows.forEach(f => {
                        const item = defaultData.find(d => d.couponId === f.couponId)
                        if (!item) {
                            const json = {

                                ...f,
                                num: 0
                            }
                            arry.push(json)
                        }

                    })
                }
                this.gridData = arry
            }
            console.log('select', data)
        },
        handlerRemove(index) {
            const objData = Object.assign([], this.gridData)
            const newData = objData.filter((item, findex) => findex !== index)
            this.gridData = newData
        },
        onSubmit() {
            const $this = this
            const postJson = {
                ...$this.form,
                couponPackageVos: $this.gridData.map(f => {
                    return {
                        couponId: f.couponId,
                        num: f.num
                    }
                })
            }
            this.$refs['form'].validate((valid) => {
                if (valid) {
                     if ($this.gridData.length<=0) {
           
                        ElMessage({
                                    message: "请选择抵扣券",
                                    type: "error",
                                });
                        return 
                     }
                    $this.loading = true
                    if (postJson.id) {
                        PackageApi.updateCouponPack(postJson, true)
                            .then(result => {
                                $this.loading = false
                                ElMessage({
                                    message: "恭喜你，更新成功",
                                    type: "success",
                                });
                                $this.$router.back()
                            }).catch(error => {
                                $this.loading = false
                                ElMessage({
                                    message: "更新失败",
                                    type: "error",
                                });
                            })
                    } else {
                        PackageApi.AddCouponPack(postJson, true)
                            .then(result => {
                                $this.loading = false
                                ElMessage({
                                    message: "恭喜你，创建成功",
                                    type: "success",
                                });
                                $this.$router.back()
                            }).catch(error => {
                                $this.loading = false
                                ElMessage({
                                    message: "创建失败",
                                    type: "error",
                                });
                            })
                    }
                }
            })



            console.log('数据提交', postJson)
        }
    },
};
</script>

<style lang="scss" scoped>
.product-add {
    padding-bottom: 50px;
}

.img {
    margin-top: 10px;
}
</style>